package com.example.demo.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Component
public class PackImpl {

    public final static String ZIP_FILE = "application/zip";
    private final static String RAR_FILE = "application/vnd.rar";

    @Value("${file.upload.zip.save.url}")
    private String fileSaveUrl;


    /**
     * 解压压缩文件 返回解压后文件夹名称
     *
     * @param uploadFile
     * @return
     */
    public String uploadPack(MultipartFile uploadFile) {
        boolean isZipPack = true;
        // 解压目录
        String packFileStr = fileSaveUrl;

        //不存在则创建
        File packFile = new File(packFileStr);
        if (!packFile.exists()) {
            packFile.mkdirs();
        }

        String contentType = uploadFile.getContentType();
        String filename = uploadFile.getOriginalFilename();

        //将压缩包保存在指定路径
        String packFilePath = packFileStr + File.separator + filename;
         if (RAR_FILE.equals(contentType)) {
            //rar解压缩处理
            isZipPack = false;
        } else {
            throw new RuntimeException("上传的压缩包格式不正确,仅支持rar和zip压缩文件!");
        }
        File file = new File(packFilePath);
        try {
            uploadFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("压缩文件到:" + packFileStr + " 失败!");
        }
        if (isZipPack) {
            //zip压缩包
            UnPackeUtil.unPackZip(file, null, packFileStr);
        } else {
            //rar压缩包
            UnPackeUtil.unPackRar(file, packFileStr);
        }
        //获取压缩包名称
        try {
            String s = readZipFile(packFileStr + "\\" + filename);
            return packFileStr + "\\" + s;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String readZipFile(String path) throws IOException {
        ZipEntry zipEntry = null;
        ZipInputStream zipInputStream = null;
        File file = new File(path);
        try {
            if (file.exists()) { //判断文件是否存在
                //解决包内文件存在中文时的中文乱码问题
                zipInputStream = new ZipInputStream(new FileInputStream(path), Charset.forName("GBK"));
                while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                    return zipEntry.getName().substring(0, zipEntry.getName().indexOf("/"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zipInputStream != null) {
                zipInputStream.close();
            }
        }
        return "";
    }


}
